# -*- coding: utf-8 -*-
from openerp.osv import osv
from openerp.osv import fields

import os
import sys
import jinja2

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.website_mshop', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)


class mshop_article(osv.osv):
    _name = 'mshop.article'

    def _get_description_editor(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        template = env.get_template('editor.html')

        for article in self.browse(cr, uid, ids, context=context):
            res.update({article.id: template.render({'editor_id': article.id, 'shop_id': article.shop_id.id})})

        return res

    _columns = {
        'name': fields.char(u'标题'),
        'image': fields.binary('图片'),
        'line_ids': fields.one2many('mshop.article.line', 'article_id', u'编辑记录'),
        'categ_id': fields.many2one('mshop.article.category', u'文章分类', domain="[('parent_id', '!=', False')]"),
        'description_editor': fields.function(_get_description_editor, type='html', string=u'编辑器'),
        'is_home': fields.boolean(u'首页'),
        'shop_id': fields.many2one('shop', u'商城', required=True),
    }

    def unlink(self, cr, uid, ids, context=None):
        for article in self.browse(cr, uid, ids, context=context):
            if article.is_home:
                raise osv.except_osv(u'错误', u'不可以删除首页记录')

        return super(mshop_article, self).unlink(cr, uid, ids, context=context)


class mshop_article_line(osv.osv):
    _name = 'mshop.article.line'

    _order = 'index asc'

    _columns = {
        'article_id': fields.many2one('mshop.article', u'文字记录'),
        'index': fields.integer(u'序号'),
        'value': fields.text(u'实际值'),
        'component': fields.char(u'组件'),
        'shop_id': fields.related('article_id', 'shop_id', type='many2one', relation='shop', string=u'商城'),
    }


class mshop_article_category(osv.osv):
    _name = 'mshop.article.category'
    _columns = 'sequence desc'

    _columns = {
        'parent_id': fields.many2one('mshop.article.category', u'一级分类', domain="[('parent_id', '=', False)]"),
        'name': fields.char(u'分类名称'),
        'sequence': fields.integer(u'顺序'),
        'is_home': fields.boolean(u'显示在首页'),
        'home_sequence': fields.integer(u'首页顺序'),
    }

    def unlink(self, cr, uid, ids, context=None):
        for row in self.browse(cr, uid, ids, context=context):
            if row.component == 'image-input':
                filename = row.value.lstrip('editor_image?filename=')
                if os.path.isfile(filename):
                    os.remove(filename)

        return super(mshop_article_category, self).unlink(cr, uid, ids, context=context)


class mshop_ad_wall(osv.osv):
    _name = 'mshop.ad.wall'

    WALL_TYPE = [
        ('big', u'大图'),
        ('small', u'小图'),
    ]

    _columns = {
        'name': fields.char(u'名称'),
        'type': fields.selection(WALL_TYPE, string=u'类型'),
        'shop_id': fields.many2one('shop', u'商城'),
        'line_ids': fields.one2many('mshop.ad.wall.line', 'wall_id', u'明细行'),
    }


class mshop_ad_wall_line(osv.osv):
    _name = 'mshop.ad.wall.line'

    _order = 'sequence asc'

    MODEL_URL_MAP = {
        'product.template': '/product/%s',
        'mshop.article': '/article/%s',
        'mshop.article.category': '/guide/category/%s'
    }

    MODEL_REFERENCE = [
        ('product.template', u'产品'),
        ('mshop.article', u'文章'),
        ('mshop.article.category', u'文章分类'),
    ]

    _columns = {
        'wall_id': fields.many2one('mshop.ad.wall', u'广告墙'),
        'sequence': fields.integer(u'序列'),
        'name': fields.char(u'标题'),
        'image': fields.binary(u'图片'),
        'url_id': fields.reference(u'链接', MODEL_REFERENCE),
    }

    def get_url(self, cr, uid, line, context=None):
        if line.url_id:
            model, model_id = line.url_id._name, str(line.url_id.id)
            return self.MODEL_URL_MAP.get(model) % model_id

        return ''
